package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.util.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String baseDir;


    //spring mvc文件上传的要求
    //要求1： 必须使用multipartfile 类型接收上传文件对象
    //要求2： multipartfile类型参数的名字必须与前端文件域表单元素name属性值一样，如果不一样
            //需要使用@RequestParam("别名“)
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();

        String fileExtName = fileName.substring(fileName.lastIndexOf("."));

        String newfileName = UUIDUtils.getUUID() + fileExtName;

        File dir=new File(baseDir);

        if(!dir.exists()){
            dir.mkdirs();
        }
        file.transferTo(new File(baseDir+newfileName));
        return R.success(newfileName);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {

        FileInputStream inputStream = new FileInputStream(baseDir + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    }



}
